*Random group assignment within ind-location-yr
quietly sort order
gen random1=runiform()
sum random1

quietly bys S J T (random1): gen order2=_n 
quietly bys S J T (random1): gen RG= order2>_N/2

*Random Groups
quietly egen JTR=group(J T RG)
quietly egen STR=group(S T RG)
quietly egen SJTR=group(S J T RG)

quietly egen tag_SJTR=tag(SJTR)
quietly egen tag_STR=tag(STR)

*Random group weights
quietly bys SJT RG:egen emp_SJTR	=total(empl)
quietly bys JT RG:egen emp_JTR		=total(empl)

quietly bys ST RG:egen emp_STR		=total(empl)
quietly gen empshare_SJTR		=emp_SJTR/emp_STR
quietly gen empindshare_JTR		=emp_SJTR/emp_JTR


*Generate FEs from microdata

*Taus
quietly reghdfe lA [aw=empl], absorb(temp_tau_R=SJTR) keepsingletons
quietly reghdfe temp_tau_R  if tag_SJTR, absorb(JT) resid keepsingletons
quietly predict tau_Rb if e(sample), resid

*CapT
quietly reghdfe tau_Rb [aw=empshare_SJT], absorb(capT_temp_R=STR)  keepsingletons
quietly reghdfe capT_temp_R if tag_STR, absorb(T) resid keepsingletons
quietly predict capT_Rb if e(sample), resid


*Manipulation to get random FEs on same rows
tempvar temp1 temp2
quietly bys SJT RG: egen `temp1'	=max(tau_Rb) if RG==0
quietly bys SJT: egen tau_Rb0		=max(`temp1') 
quietly bys SJT RG: egen `temp2'	=max(tau_Rb) if RG==1
quietly bys SJT: egen tau_Rb1		=max(`temp2') 

tempvar temp1 temp2
quietly bys ST RG: egen `temp1'=max(capT_Rb) if RG==0
quietly bys ST: egen capT_Rb0=max(`temp1') 
quietly bys ST RG: egen `temp2'=max(capT_Rb) if RG==1
quietly bys ST: egen capT_Rb1=max(`temp2')

quietly keep if RG==0
